<template>
  <div class="certification-layout">
    <!-- 左侧导航栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <div class="logo">
          <img src="/666.png" alt="Logo" />
        </div>
        <div class="logo-text">{{ $t('enterpriseCertification.logoText') }}</div>
      </div>
      
      <div class="sidebar-menu">
        <div 
          class="menu-item enterprise-info-item" 
          :class="{ active: currentModule === 'enterprise-certification' }"
          @click="switchModule('enterprise-certification')"
        >
          <div class="enterprise-info">
            <div class="enterprise-logo" v-if="getCompanyLogo()">
              <img :src="getCompanyLogo()" alt="企业Logo" />
            </div>
            <div class="enterprise-logo default-logo" v-else>
              <el-icon size="20"><OfficeBuilding /></el-icon>
            </div>
            <div class="enterprise-details">
              <div class="enterprise-name">{{ getCompanyName() }}</div>
              <div class="enterprise-code" v-if="getSocialCreditCode()">
                {{ getSocialCreditCode() }}
              </div>
            </div>
          </div>
          <div class="menu-icon">
            <el-icon size="16"><ArrowUp /></el-icon>
            <el-icon size="16"><ArrowDown /></el-icon>
          </div>
        </div>
        <div 
          class="menu-item" 
          @click="goBack"
        >
          <span class="menu-text">{{ $t('enterpriseCertification.back') }}</span>
        </div>

      </div>
    </div>

    <!-- 右侧主内容区 -->
    <div class="main-content">
      <!-- 企业认证模块 -->
      <div class="certification-container">
        <div class="certification-header">
          <h1 class="page-title">{{ $t('enterpriseCertification.pageTitle') }}</h1>
        </div>

        <!-- 企业信息展示 -->
        <div class="company-profile-card" v-if="certificationData">
          <div class="company-header">
            <div class="company-name-container">
              <h2 class="company-name">{{ certificationData.companyFullName }}</h2>
              <div class="certification-status-badge" v-if="certificationStatus" :style="{ borderColor: getStatusColor() }">
                <el-icon :color="getStatusColor()" size="16">
                  <component :is="getStatusIcon()" />
                </el-icon>
                <span class="status-text" :style="{ color: getStatusColor() }">
                  {{ getStatusText() }}
                </span>
              </div>
            </div>
          </div>
          
          <!-- 调试信息：显示认证状态详情 -->
          <div class="debug-info" style="margin-top: 16px; padding: 12px; background: #f5f5f5; border-radius: 6px; font-size: 12px; color: #666;">
            <div><strong>认证状态详情:</strong></div>
            <div>状态: {{ certificationStatus?.status || '未知' }}</div>
            <div>消息: {{ certificationStatus?.message || '无' }}</div>
            <div>公司名称: {{ certificationStatus?.companyName || '无' }}</div>
            <div>最后检查: {{ certificationStatus?.lastCheck ? new Date(certificationStatus.lastCheck).toLocaleString() : '无' }}</div>
          </div>
          
          <div class="company-details">
            <div class="detail-row">
              <div class="detail-item">
                <span class="label">{{ $t('enterpriseCertification.mainBusiness') }}</span>
                <span class="value">{{ certificationData.mainBusiness }}</span>
              </div>
              <div class="detail-item">
                <span class="label">{{ $t('enterpriseCertification.companySize') }}</span>
                <span class="value">{{ getCompanySizeText(certificationData.companyScale) }}</span>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-item">
                <span class="label">{{ $t('enterpriseCertification.officialWebsite') }}</span>
                <span class="value">{{ certificationData.officialWebsiteUrl }}</span>
              </div>
              <div class="detail-item">
                <span class="label">{{ $t('enterpriseCertification.companyLocation') }}</span>
                <span class="value">{{ certificationData.companyAddress }}</span>
              </div>
            </div>
          </div>
          
          <div class="business-tags" v-if="certificationData.mainBusiness">
            <span 
              v-for="business in getBusinessTags(certificationData.mainBusiness)" 
              :key="business" 
              class="business-tag"
            >
              {{ business }}
            </span>
          </div>
          
          <div class="company-advantages">
            <h4>{{ $t('enterpriseCertification.companyAdvantages') }}</h4>
            <p>{{ $t('enterpriseCertification.companyAdvantagesDesc') }}</p>
            <ul>
              <li v-if="certificationData.mainBusiness">{{ $t('enterpriseCertification.businessScope') }}{{ certificationData.mainBusiness }}{{ $t('enterpriseCertification.businessScopeEnd') }}</li>
              <li v-if="certificationData.companyScale">{{ $t('enterpriseCertification.companyScale') }}{{ getCompanySizeText(certificationData.companyScale) }}{{ $t('enterpriseCertification.companyScaleEnd') }}</li>
              <li v-if="certificationData.companyAddress">{{ $t('enterpriseCertification.locationAdvantage') }}{{ getLocationText(certificationData.companyAddress) }}</li>
              <li>{{ $t('enterpriseCertification.legalQualification') }}</li>
              <li>{{ $t('enterpriseCertification.reliableInfo') }}</li>
            </ul>
          </div>
          
          <div class="company-introduction">
            <h3 class="intro-title">{{ $t('enterpriseCertification.companyIntroduction') }}</h3>
            <div class="intro-content">
              <p>{{ certificationData.companyIntroduction }}</p>
            </div>
          </div>
        </div>
        
        <!-- 未认证状态提示 -->
        <div class="no-certification" v-else>
          <div class="no-certification-content">
            <el-icon size="48" color="#909399"><Document /></el-icon>
            <h3>{{ $t('enterpriseCertification.noCertification') }}</h3>
            <p>{{ $t('enterpriseCertification.noCertificationDesc') }}</p>
          </div>
        </div>
      </div>




    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  CircleCheckFilled, 
  Clock, 
  Warning,
  Document,
  Check,
  InfoFilled,
  Search,
  User,
  Lightning,
  Setting,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'
import { userApi } from '../../api'
import { certificationManager } from '../../utils/certification'
import { useI18n } from 'vue-i18n'

const { t, locale } = useI18n()

// 语言检测逻辑
const detectLanguage = () => {
  const savedLang = localStorage.getItem('lang')
  if (savedLang && (savedLang === 'zh' || savedLang === 'en')) {
    locale.value = savedLang
  } else {
    // 如果没有保存的语言设置，默认使用中文
    locale.value = 'zh'
    localStorage.setItem('lang', 'zh')
  }
}


const router = useRouter()
const route = useRoute()

// 响应式数据
const certificationFormRef = ref()
const licenseUploadRef = ref()
const logoUploadRef = ref()
const submitting = ref(false)
const certificationStatus = ref(null)
const certificationData = ref(null)



// 认证表单数据
const certificationForm = reactive({
  companyName: '',
  creditCode: '',
  businessLicense: [],
  operatorName: '',
  operatorPosition: '',
  phone: '',
  email: '',
  companyLogo: [],
  companyDescription: '',
  mainBusiness: [],
  website: '',
  industry: '',
  companySize: ''
})

// 表单验证规则
const certificationRules = {
  companyName: [
    { required: true, message: t('enterpriseCertification.companyNameRequired'), trigger: 'blur' },
    { min: 2, max: 100, message: t('enterpriseCertification.companyNameLength'), trigger: 'blur' }
  ],
  creditCode: [
    { required: true, message: t('enterpriseCertification.creditCodeRequired'), trigger: 'blur' },
    { pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/, message: t('enterpriseCertification.creditCodeInvalid'), trigger: 'blur' }
  ],
  businessLicense: [
    { required: true, message: t('enterpriseCertification.businessLicenseRequired'), trigger: 'change' },
    { type: 'array', min: 1, message: t('enterpriseCertification.businessLicenseRequired'), trigger: 'change' },
    { validator: (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error(t('enterpriseCertification.businessLicenseRequired')))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
  operatorName: [
    { required: true, message: t('enterpriseCertification.operatorNameRequired'), trigger: 'blur' }
  ],
  operatorPosition: [
    { required: true, message: t('enterpriseCertification.operatorPositionRequired'), trigger: 'blur' }
  ],
  phone: [
    { required: true, message: t('enterpriseCertification.phoneRequired'), trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: t('enterpriseCertification.phoneInvalid'), trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: t('enterpriseCertification.emailInvalid'), trigger: 'blur' }
  ],
  companyDescription: [
    { required: true, message: t('enterpriseCertification.companyDescriptionRequired'), trigger: 'blur' },
    { min: 10, max: 500, message: t('enterpriseCertification.companyDescriptionLength'), trigger: 'blur' }
  ],
  mainBusiness: [
    { required: true, message: t('enterpriseCertification.mainBusinessRequired'), trigger: 'change' },
    { type: 'array', min: 1, message: t('enterpriseCertification.mainBusinessMin'), trigger: 'change' }
  ],
  industry: [
    { required: true, message: t('enterpriseCertification.industryRequired'), trigger: 'change' }
  ],
  companySize: [
    { required: true, message: t('enterpriseCertification.companySizeRequired'), trigger: 'change' }
  ]
}

// 选项数据
const businessOptions = [
  { value: '软件开发', label: t('enterpriseCertification.softwareDevelopment') },
  { value: '人工智能', label: t('enterpriseCertification.artificialIntelligence') },
  { value: '电子商务', label: t('enterpriseCertification.ecommerce') },
  { value: '金融服务', label: t('enterpriseCertification.financialServices') },
  { value: '教育培训', label: t('enterpriseCertification.educationTraining') },
  { value: '医疗健康', label: t('enterpriseCertification.healthcare') },
  { value: '制造业', label: t('enterpriseCertification.manufacturing') },
  { value: '贸易进出口', label: t('enterpriseCertification.tradeImportExport') },
  { value: '咨询服务', label: t('enterpriseCertification.consultingServices') },
  { value: '其他', label: t('enterpriseCertification.other') }
]

const industryOptions = [
  { value: 'technology', label: t('enterpriseCertification.technologyInternet') },
  { value: 'finance', label: t('enterpriseCertification.financeInvestment') },
  { value: 'education', label: t('enterpriseCertification.educationTraining') },
  { value: 'healthcare', label: t('enterpriseCertification.healthcareHealth') },
  { value: 'manufacturing', label: t('enterpriseCertification.manufacturing') },
  { value: 'trade', label: t('enterpriseCertification.tradeImportExport') },
  { value: 'consulting', label: t('enterpriseCertification.consultingService') },
  { value: 'retail', label: t('enterpriseCertification.retailEcommerce') },
  { value: 'real_estate', label: t('enterpriseCertification.realEstate') },
  { value: 'energy', label: t('enterpriseCertification.energyEnvironment') },
  { value: 'media', label: t('enterpriseCertification.mediaEntertainment') },
  { value: 'other', label: t('enterpriseCertification.other') }
]

const companySizeOptions = [
  { value: '1-10', label: t('enterpriseCertification.size1To10') },
  { value: '11-50', label: t('enterpriseCertification.size11To50') },
  { value: '51-100', label: t('enterpriseCertification.size51To100') },
  { value: '101-500', label: t('enterpriseCertification.size101To500') },
  { value: '501-1000', label: t('enterpriseCertification.size501To1000') },
  { value: '1000+', label: t('enterpriseCertification.size1000Plus') }
]

// 计算属性
const isCertified = computed(() => {
  return certificationStatus.value?.status === 'approved'
})

const isUnsubmitted = computed(() => {
  return certificationStatus.value?.status === 'unsubmitted'
})



// 上传相关 - 禁用自动上传，在提交时一起处理
const uploadAction = '#' // 禁用自动上传
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('access_token')}`
}

// 方法
const checkCertificationStatus = async () => {
  try {
    // 再次检查token
    const token = localStorage.getItem('access_token')
    if (!token) {
      throw new Error('没有有效的认证token')
    }
    
    const status = await certificationManager.getStatus()
    certificationStatus.value = status
    
    // 如果认证成功，获取企业完整信息
    if (status.status === 'approved') {
      // 先设置基本信息
      certificationData.value = {
        companyFullName: status.companyName,
        socialCreditCode: status.socialCreditCode
      }
      
      // 获取企业完整信息
      await fetchEnterpriseProfile()
    }
  } catch (error) {
    console.error(t('enterpriseCertification.getStatusFailed'), error)
    
    // 如果是401错误，说明token无效
    if (error.message.includes('401') || error.message.includes('token')) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
      return
    }
    
    // 显示错误状态
    certificationStatus.value = {
      status: 'unsubmitted',
      message: '未提交认证申请',
      error: error.message
    }
  }
}





// 认证状态处理方法
const getStatusText = () => {
  switch (certificationStatus.value?.status) {
    case 'approved': return t('enterpriseCertification.statusApproved')
    case 'pending_review': return t('enterpriseCertification.statusPendingReview')
    case 'rejected': return t('enterpriseCertification.statusRejected')
    case 'unsubmitted': return t('enterpriseCertification.statusUnsubmitted')
    default: return t('enterpriseCertification.statusUncertified')
  }
}

const getStatusColor = () => {
  switch (certificationStatus.value?.status) {
    case 'approved': return '#409EFF' // 蓝色
    case 'pending_review': return '#E6A23C' // 黄色
    case 'rejected': return '#F56C6C' // 红色
    case 'unsubmitted': return '#909399' // 灰色
    default: return '#909399'
  }
}

const getStatusIcon = () => {
  switch (certificationStatus.value?.status) {
    case 'approved': return Check
    case 'pending_review': return Clock
    case 'rejected': return Warning
    case 'unsubmitted': return Document
    default: return Document
  }
}

// 获取企业信息的方法
const getCompanyName = () => {
  // 优先使用认证数据中的企业名称
  if (certificationData.value?.companyFullName) {
    return certificationData.value.companyFullName
  }
  // 如果没有认证数据，使用表单中的企业名称
  if (certificationForm.companyName) {
    return certificationForm.companyName
  }
  return t('enterpriseCertification.pageTitle')
}

const getSocialCreditCode = () => {
  // 优先使用认证数据中的统一社会信用代码
  if (certificationData.value?.socialCreditCode) {
    return certificationData.value.socialCreditCode
  }
  // 如果没有认证数据，使用表单中的统一社会信用代码
  if (certificationForm.creditCode) {
    return certificationForm.creditCode
  }
  return null
}

const getCompanyLogo = () => {
  // 优先使用认证数据中的企业logo
  if (certificationData.value?.companyLogo) {
    return certificationData.value.companyLogo
  }
  // 如果没有认证数据，使用表单中的企业logo
  if (certificationForm.companyLogo && certificationForm.companyLogo.length > 0) {
    const logoFile = certificationForm.companyLogo[0]
    if (logoFile.url) {
      return logoFile.url
    }
    if (logoFile.raw) {
      return URL.createObjectURL(logoFile.raw)
    }
  }
  return null
}

// 数据处理方法
const getCompanySizeText = (size) => {
  const sizeMap = {
    '1-10': '1-10人',
    '11-50': '11-50人',
    '51-100': '51-100人',
    '101-500': '101-500人',
    '501-1000': '501-1000人',
    '1000+': '1000人以上'
  }
  return sizeMap[size] || size
}

const getBusinessTags = (mainBusiness) => {
  if (!mainBusiness) return []
  // 将主要业务按逗号分割成标签
  return mainBusiness.split(',').map(item => item.trim()).filter(item => item)
}

const fetchEnterpriseProfile = async () => {
  try {
    const token = localStorage.getItem('access_token')
    if (!token) {
      throw new Error('没有有效的认证token')
    }
    
    
    
    const response = await fetch('/api/api/v1/enterprise/profile/complete', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      
      if (result.code === 'SUCCESS' && result.data && result.data.companyInfo) {
        // 从companyInfo中获取企业信息
        const companyInfo = result.data.companyInfo
        
        // 更新认证数据
        certificationData.value = {
          ...certificationData.value,
          mainBusiness: companyInfo.mainBusiness,
          companyScale: companyInfo.companyScale,
          officialWebsiteUrl: companyInfo.officialWebsiteUrl,
          companyAddress: companyInfo.companyAddress,
          companyIntroduction: companyInfo.companyIntroduction,
          socialCreditCode: companyInfo.socialCreditCode,
          companyLogo: companyInfo.companyLogo
        }
      }
    } else {
      console.error(t('enterpriseCertification.getEnterpriseInfoFailed'), response.status)
    }
  } catch (error) {
    console.error(t('enterpriseCertification.getEnterpriseInfoFailed'), error)
  }
}

const getLocationText = (address) => {
  if (!address) return address
  // 提取省份信息
  const provinceMatch = address.match(/中国·(.+?)省/)
  if (provinceMatch) {
    return provinceMatch[1] + '省'
  }
  return address
}





const handleLicenseChange = (file, fileList) => {
  if (file && file.raw) {
    const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.raw.type)
    const isLt10M = file.raw.size / 1024 / 1024 < 10

    if (!isValidType) {
      ElMessage.error(t('enterpriseCertification.invalidFileType'))
      return
    }
    if (!isLt10M) {
      ElMessage.error(t('enterpriseCertification.fileTooLarge'))
      return
    }
    
    // 保存文件到表单数据
    certificationForm.businessLicense = [file]
    
    ElMessage.success(t('enterpriseCertification.businessLicenseSelected'))
  }
}

const handleLogoChange = (file, fileList) => {
  if (file && file.raw) {
    const isValidType = ['image/jpeg', 'image/png'].includes(file.raw.type)
    const isLt5M = file.raw.size / 1024 / 1024 < 5

    if (!isValidType) {
      ElMessage.error(t('enterpriseCertification.logoInvalidFormat'))
      return
    }
    if (!isLt5M) {
      ElMessage.error(t('enterpriseCertification.logoTooLarge'))
      return
    }
    
    // 保存文件到表单数据
    certificationForm.companyLogo = [file]
    
    ElMessage.success(t('enterpriseCertification.companyLogoSelected'))
  }
}



const onUploadError = (error) => {
  // 检查是否是接口未实现的错误
  if (error.message && error.message.includes('No static resource')) {
    ElMessage.error(t('enterpriseCertification.uploadNotAvailable'))
  } else {
    ElMessage.error(t('enterpriseCertification.uploadFailed'))
  }
}

const submitCertification = async () => {
  try {
    const valid = await certificationFormRef.value.validate()
    
    if (!valid) {
      // 获取具体的验证错误信息
      const fields = certificationFormRef.value.fields
      const errors = []
      
      for (const field of fields) {
        if (field.validateState === 'error') {
          errors.push(field.label || field.prop)
        }
      }
      
      if (errors.length > 0) {
        ElMessage.error(`${t('enterpriseCertification.checkFields')}${errors.join(', ')}`)
      } else {
        ElMessage.error(t('enterpriseCertification.checkFormInfo'))
      }
      
      return
    }

    submitting.value = true

    // 检查文件是否已上传
    if (!certificationForm.businessLicense.length) {
      ElMessage.error('请上传营业执照')
      return
    }

    // 获取用户ID
    const userId = localStorage.getItem('user_id')
    if (!userId) {
      ElMessage.error('用户信息获取失败，请重新登录')
      router.push('/login')
      return
    }

    // 构建certificationData JSON对象
    const certificationData = {
      enterpriseUserId: parseInt(userId),
      companyFullName: certificationForm.companyName,
      socialCreditCode: certificationForm.creditCode,
      operatorName: certificationForm.operatorName,
      operatorPosition: certificationForm.operatorPosition,
      contactPhoneNumber: certificationForm.phone,
      contactEmail: certificationForm.email || '',
      companyIntroduction: certificationForm.companyDescription,
      mainBusiness: certificationForm.mainBusiness && certificationForm.mainBusiness.length > 0 
        ? certificationForm.mainBusiness.join(', ') 
        : '',
      officialWebsiteUrl: certificationForm.website || '',
      industry: certificationForm.industry,
      companyScale: certificationForm.companySize,
      companyAddress: '' // 如果需要地址字段，可以添加到表单中
    }



    // 生产模式：构建multipart/form-data请求
    const formData = new FormData()
    
    // 添加JSON数据
    const jsonBlob = new Blob([JSON.stringify(certificationData)], {
      type: 'application/json'
    })
    formData.append('certificationData', jsonBlob, 'certificationData.json')
    
    // 添加营业执照文件
    const businessLicenseFile = certificationForm.businessLicense[0]
    if (businessLicenseFile && businessLicenseFile.raw) {
      // 生成安全的文件名
      const originalName = businessLicenseFile.name
      const fileExtension = originalName.split('.').pop()
      const timestamp = Date.now()
      const safeFileName = `business_license_${timestamp}.${fileExtension}`
      
      formData.append('business_license_file', businessLicenseFile.raw, safeFileName)
    }
    
    // 添加公司Logo文件
    const companyLogoFile = certificationForm.companyLogo[0]
    if (companyLogoFile && companyLogoFile.raw) {
      // 生成安全的文件名
      const originalName = companyLogoFile.name
      const fileExtension = originalName.split('.').pop()
      const timestamp = Date.now()
      const safeFileName = `company_logo_${timestamp}.${fileExtension}`
      
      formData.append('company_logo_file', companyLogoFile.raw, safeFileName)
    }

    // 发送请求
    const response = await fetch('/api/api/v1/enterprise/certification/apply', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
      },
      body: formData
    })
    
    const result = await response.json()

    if (response.ok && result.code === 'SUCCESS') {
      ElMessage.success(result.message || '认证申请提交成功，请等待审核')
      certificationManager.clearCache()
      // 更新本地数据，确保左侧导航栏能显示最新信息
      if (certificationForm.companyName) {
        certificationData.value = {
          ...certificationData.value,
          companyFullName: certificationForm.companyName,
          socialCreditCode: certificationForm.creditCode
        }
      }
      await checkCertificationStatus()
    } else {
      // 处理不同的错误情况
      let errorMessage = '提交失败，请重试'
      
      switch (result.code) {
        case 'INVALID_INPUT':
          errorMessage = '关键认证信息不完整，请检查后重试'
          break
        case 'INVALID_ENTERPRISE_USER_ID':
          errorMessage = '用户信息无效，请重新登录'
          router.push('/login')
          break
        case 'SOCIAL_CREDIT_CODE_EXISTS':
          errorMessage = '该社会信用代码已被注册'
          break
        case 'DATA_INTEGRITY_VIOLATION':
          errorMessage = '数据提交失败，请检查输入内容是否符合要求'
          break
        case 'FILE_UPLOAD_ERROR':
          errorMessage = '文件上传失败，请稍后重试'
          break
        case 'INTERNAL_SERVER_ERROR':
          errorMessage = '服务器内部错误，请稍后重试'
          break
        default:
          errorMessage = result.error || result.message || '提交失败，请重试'
      }
      
      ElMessage.error(errorMessage)
    }
      } catch (error) {
      // 显示详细的错误信息
      let errorMessage = '网络错误，请稍后重试'
      
      if (error.response) {
        // 服务器返回了错误响应
        const { status, data } = error.response
        
        if (data && data.error) {
          errorMessage = data.error
        } else if (data && data.message) {
          errorMessage = data.message
        } else {
          errorMessage = `服务器错误 (${status})`
        }
      } else if (error.message) {
        // 网络错误或其他错误
        errorMessage = error.message
      }
      
      ElMessage.error(errorMessage)
    } finally {
      submitting.value = false
    }
}

const resetForm = () => {
  certificationFormRef.value?.resetFields()
  certificationForm.businessLicense = []
  certificationForm.companyLogo = []
}

const goBack = () => {
  router.go(-1)
}



// 导航路由管理




// 检查登录状态
const checkLoginStatus = () => {
  const token = localStorage.getItem('access_token')
  const userType = localStorage.getItem('user_type')
  
  if (!token) {
    ElMessage.error('登录已过期，请重新登录')
    router.push('/login')
    return false
  }
  
  if (userType !== 'enterprise') {
    ElMessage.error('权限不足')
    router.push('/')
    return false
  }
  
  return true
}

// 生命周期
onMounted(async () => {
  // 检测并设置语言
  detectLanguage()
  
  // 首先检查登录状态
  if (!checkLoginStatus()) {
    return
  }
  
  await checkCertificationStatus()
})
</script>

<style scoped>
.certification-layout {
  display: flex;
  min-height: 100vh;
}

.sidebar {
  width: 250px;
  background-color: #ffffff;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 10;
  border-right: 1px solid #e0e0e0;
}

.sidebar-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  cursor: pointer;
}

.logo {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
}

.logo img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 8px;
}

.logo-text {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.sidebar-menu {
  width: 100%;
  margin-bottom: 30px;
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  width: 100%;
  user-select: none;
  position: relative;
  border-radius: 0;
}

.menu-item:hover {
  background-color: #f5f5f5;
}

.menu-item.active {
  background: #ffffff;
  color: #409EFF;
  border-radius: 0;
  border: 1px solid #409EFF;
}

.menu-item.active .menu-text,
.menu-item.active .menu-icon {
  color: #409EFF;
}



.menu-text {
  font-size: 16px;
  font-weight: 500;
  position: relative;
  z-index: 2;
  pointer-events: none;
}

.menu-icon {
  font-size: 16px;
  position: relative;
  z-index: 2;
  pointer-events: none;
  display: flex;
  flex-direction: column;
  gap: 1px;
  align-items: center;
  color: #666666;
}

.menu-item.active .menu-icon {
  color: #409EFF;
}

.menu-item:hover .menu-icon {
  color: #333333;
}

/* 企业信息样式 */
.enterprise-info-item {
  padding: 8px 12px !important;
}

.enterprise-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.enterprise-logo {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  background-color: #409EFF;
  flex-shrink: 0;
}

.enterprise-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.enterprise-logo.default-logo {
  background-color: #409EFF;
  color: white;
}

.enterprise-details {
  flex: 1;
  min-width: 0;
}

.enterprise-name {
  font-size: 12px;
  font-weight: 500;
  color: #303133;
  line-height: 1.2;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.enterprise-code {
  font-size: 10px;
  color: #909399;
  line-height: 1.2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}



.main-content {
  flex: 1;
  margin-left: 250px; /* Adjust based on sidebar width */
  padding: 20px;
  background-color: #ffffff;
}

/* 不同模块的容器样式 */
.enterprise-home-container,
.enterprise-post-container,
.enterprise-applications-container {
  width: 100%;
  height: 100%;
}

.certification-container {
  width: 100%;
}

.certification-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background-color: transparent;
  border-radius: 0;
  box-shadow: none;
}

.certification-header {
  text-align: left;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #EBEEF5;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.page-subtitle {
  font-size: 16px;
  color: #606266;
}





.certification-form-card {
  margin-bottom: 30px;
  border: 1px solid #e0e0e0;
  border-radius: 0;
  box-shadow: none;
}

.form-header {
  text-align: left;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.form-header h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.form-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.certification-form {
  margin-top: 20px;
}

.form-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.form-row {
  display: flex;
  gap: 30px;
  margin-bottom: 20px;
}

.form-column {
  flex: 1;
}

.form-column :deep(.el-form-item) {
  margin-bottom: 20px;
}

.form-column :deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

.form-column :deep(.el-input__wrapper) {
  border-radius: 4px;
}

.form-column :deep(.el-select) {
  width: 100%;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
}

.form-actions .el-button {
  margin: 0 10px;
}



:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  line-height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  transition: border-color 0.3s ease;
}

:deep(.el-upload--picture-card:hover) {
  border-color: #409EFF;
}

:deep(.el-upload--picture-card .el-icon) {
  font-size: 28px;
  color: #8c939d;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

.form-actions .el-button {
  padding: 12px 24px;
  font-size: 16px;
}

/* 企业信息展示样式 */
.company-profile-card {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 0;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: none;
}

.company-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.company-name-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

.company-name {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  text-align: left;
}

.certification-status-badge {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid;
  font-size: 12px;
  font-weight: 500;
}

.certification-status-badge .status-text {
  font-weight: 500;
}

.company-details {
  margin-bottom: 25px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  text-align: left;
}

.detail-item {
  flex: 1;
  display: flex;
  align-items: center;
}

.detail-item .label {
  font-size: 14px;
  color: #909399;
  margin-right: 10px;
  min-width: 80px;
}

.detail-item .value {
  font-size: 16px;
  color: #303133;
  font-weight: 500;
}

.business-tags {
  margin-bottom: 30px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.business-tag {
  background-color: #f5f5f5;
  color: #666666;
  padding: 6px 12px;
  border-radius: 0;
  font-size: 14px;
  border: 1px solid #e0e0e0;
}

.company-advantages {
  margin-bottom: 30px;
  text-align: left;
}

.company-advantages h4 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
}

.company-advantages p {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
  line-height: 1.6;
}

.company-advantages ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.company-advantages li {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  padding-left: 20px;
  position: relative;
  line-height: 1.6;
}

.company-advantages li:before {
  content: "•";
  color: #409EFF;
  font-weight: bold;
  position: absolute;
  left: 0;
}

.company-introduction {
  text-align: left;
}

.intro-title {
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 20px;
  text-align: left;
}

.intro-content {
  background-color: #f9f9f9;
  border: 1px solid #e0e0e0;
  border-radius: 0;
  padding: 20px;
  line-height: 1.8;
}

.intro-content p {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
  text-align: left;
}

.intro-content p:last-child {
  margin-bottom: 0;
}



/* 未认证状态样式 */
.no-certification {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 0;
  padding: 60px 30px;
  margin-bottom: 30px;
  text-align: center;
  box-shadow: none;
}

.no-certification-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.no-certification-content h3 {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.no-certification-content p {
  font-size: 14px;
  color: #606266;
  margin: 0;
  line-height: 1.6;
}
</style> 